package com.library.controller;

import com.library.bean.Book;
import com.library.bean.Lend;
import com.library.bean.ReaderCard;
import com.library.service.BookService;
import com.library.service.LendService;
import com.library.util.Page;
import com.library.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/*图书相关Controller层*/
@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    @Autowired
    private LendService lendService;

    /*每页显示记录数*/
    public final int everyPage = 10;
    //测试时使用
//     public final  int everyPage = 3;

    /*将接受的日期String类型转换为Date类型*/
    Date getDate(String pubstr) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            return df.parse(pubstr);
        } catch (ParseException e) {
            e.printStackTrace();
            return new Date();
        }
    }

    //获取分页信息
    Page getPage(HttpServletRequest request, ArrayList<Book> books) {
        //获取总记录数
        int totalCount = books.size();
        //点击链接重新获取当前页
        String scurrentPage = request.getParameter("currentPage");
        int currentPage = 1; //当前页，默认1
        if (scurrentPage == null) {
            currentPage = 1;//从第一页开始访问
        } else {
            currentPage = Integer.parseInt(scurrentPage);
        }
        //分页信息
        Page page = PageUtil.createPage(everyPage, totalCount, currentPage);
        return page;
    }

    /*管理员   界面头部*/
    @RequestMapping("/admin_header.html")
    public ModelAndView admin_header() {
        return new ModelAndView("admin_header");
    }

    /*管理员  查看全部图书*/
    @RequestMapping("/admin_books.html")
    public ModelAndView adminBooks(HttpServletRequest request) {
        ArrayList<Class> classList = bookService.queryAllClassInfo();   //图书类别   登录时session存储更好
        ArrayList<Book> books = bookService.getAllBooks();              //全部图书集合
        Page page = getPage(request, books);                             //分页数据信息
        ArrayList<Book> booksByPage = bookService.getAllBooksByPage(page);//当前页的图书集合
        ModelAndView modelAndView = new ModelAndView("admin_books");
        modelAndView.addObject("classList", classList);
        modelAndView.addObject("page", page);
        modelAndView.addObject("url", "/admin_books.html");
        modelAndView.addObject("books", booksByPage);
        return modelAndView;
    }

    /*管理员   模糊查询图书  (书名、作者）*/
    @RequestMapping("/querybook.html")
    public ModelAndView queryBookDo(HttpServletRequest request, String bookName) {
        ModelAndView modelAndView = new ModelAndView("admin_books");
        ArrayList<Class> classList = bookService.queryAllClassInfo();           //登录时session存储更好
        modelAndView.addObject("classList", classList);
        ArrayList<Book> books = bookService.queryBook(bookName);               //模糊查询图书集合
        if (books.size() > 0) {
            Page page = getPage(request, books);                               //分页数据信息
            ArrayList<Book> booksByPage = bookService.queryBookByPage(bookName, page.getBeginIndex(), everyPage);//当前页的图书集合
            modelAndView.addObject("page", page);
            modelAndView.addObject("url", "/querybook.html");
            modelAndView.addObject("books", booksByPage);
            modelAndView.addObject("bookName", bookName);
            return modelAndView;
        } else {
            ModelAndView modelAndView2 = new ModelAndView("admin_books", "error", "没有匹配的图书");
            modelAndView2.addObject("classList", classList);
            return modelAndView2;
        }
    }

    /*管理员   模糊查询图书  (图书类别id）*/
    @RequestMapping("/querybook2.html")
    public ModelAndView queryBookDo2(HttpServletRequest request, long classId) {
        ModelAndView modelAndView = new ModelAndView("admin_books");
        ArrayList<Class> classList = bookService.queryAllClassInfo();           //登录时session存储更好
        modelAndView.addObject("classList", classList);
        ArrayList<Book> books = bookService.queryBook2(classId);
        if (books.size() > 0) {
            Page page = getPage(request, books);                                  //分页数据信息
            ArrayList<Book> booksByPage = bookService.queryBook2ByPage(classId, page.getBeginIndex(), everyPage);//当前页的图书集合
            modelAndView.addObject("books", booksByPage);
            modelAndView.addObject("page", page);
            modelAndView.addObject("url", "/querybook2.html");
            modelAndView.addObject("classId", classId);
            return modelAndView;
        } else {
            ModelAndView modelAndView2 = new ModelAndView("admin_books", "error", "没有匹配的图书");
            modelAndView2.addObject("classList", classList);
            return modelAndView2;
        }
    }

    /*管理员  查看图书详情*/
    @RequestMapping("/admin_book_detail.html")
    public ModelAndView adminBookDetail(HttpServletRequest request) {
        long bookId = Long.parseLong(request.getParameter("bookId"));
        Book book = bookService.getBook(bookId);
        ModelAndView modelAndView = new ModelAndView("admin_book_detail");
        modelAndView.addObject("detail", book);
        return modelAndView;
    }

    /*管理员 添加图书信息(第一步：跳转带填写信息的界面)    add */
    @RequestMapping("/book_add.html")
    public ModelAndView addBook() {
        return new ModelAndView("admin_book_add");
    }

    /*管理员 添加图书信息(第二步：将填写的信息存储到数据库)      add*/
    @RequestMapping("/book_add_do.html")
    public String addBookDo(@RequestParam(value = "pubstr") String pubstr, Book book, RedirectAttributes redirectAttributes) {
        book.setPubdate(getDate(pubstr));
        if (bookService.addBook(book)) {
            redirectAttributes.addFlashAttribute("succ", "图书添加成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "图书添加失败！");
        }
        return "redirect:/admin_books.html";
    }

    /*管理员 修改图书信息(第一步：读取员来的信息)       update*/
    @RequestMapping("/updatebook.html")
    public ModelAndView bookEdit(HttpServletRequest request) {
        long bookId = Long.parseLong(request.getParameter("bookId"));
        Book book = bookService.getBook(bookId);
        ModelAndView modelAndView = new ModelAndView("admin_book_edit");
        modelAndView.addObject("detail", book);
        //下面代码目的    编辑图书结束后会返回编辑之前所在页       （debug判断方便观察)
        if(!"".equals(request.getParameter("bookName"))){
            modelAndView.addObject("bookName", request.getParameter("bookName")); //add
        }
        if(!"".equals(request.getParameter("classId"))){
            modelAndView.addObject("classId", request.getParameter("classId")); //add
        }
        modelAndView.addObject("currentPage", request.getParameter("currentPage")); //add

        return modelAndView;
    }

    /*管理员 修改图书信息(第二步：修改信息)      update*/
    //编辑时某个属性为null，点击确定跳到这个url  http://localhost:8080/book_edit_do.html?bookId=1&currentPage=
    //但是无法接收的currentPage  就会报错
    @RequestMapping("/book_edit_do.html")
    public String bookEditDo(@RequestParam(value = "pubstr") String pubstr, Book book,HttpServletRequest request, RedirectAttributes redirectAttributes) {
        System.out.println("当前页为："+request.getParameter("currentPage"));
        book.setPubdate(getDate(pubstr));
            if (bookService.editBook(book)) {
            redirectAttributes.addFlashAttribute("succ", "图书修改成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "图书修改失败！");
        }

        //下面代码目的    编辑图书结束后会返回编辑之前所在页
        //(比如模糊查询类别id，并点击第二页 ，编辑第二页的信息，避免确定后还会返回到全部图书界面)
        //为什么这里用request.getParameter("bookName")!=null 上面用!"".equals(request.getParameter("bookName"))
        //因为如果admin_book_edit.jsp action没有bookName=${bookName}，request.getParameter("bookName")就是null， !"".equals(null) 就会为true  ，导致逻辑错误
        if(request.getParameter("bookName")!=null ){
            System.out.println("模糊查询输入的中文："+request.getParameter("bookName"));
            try {
                String bookName = URLEncoder.encode(request.getParameter("bookName"),"UTF-8");
                return "redirect:/querybook.html?bookName="+bookName+"&currentPage="+request.getParameter("currentPage");
            }catch (Exception e){
                System.out.println("encode方法会报出异常，没办法");
            }
        }
        //admin_book_edit.jsp  action没有classId=${classId}
        if(request.getParameter("classId")!=null ){
            return "redirect:/querybook2.html?classId="+request.getParameter("classId")+"&currentPage="+request.getParameter("currentPage");
        }
        return "redirect:/admin_books.html?currentPage="+request.getParameter("currentPage");
    }

    /*管理员 删除图书*/
    @RequestMapping("/deletebook.html")
    public String deleteBook(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        long bookId = Long.parseLong(request.getParameter("bookId"));
        if (bookService.deleteBook(bookId)) {
            redirectAttributes.addFlashAttribute("succ", "图书删除成功！");
        } else {
            redirectAttributes.addFlashAttribute("error", "图书删除失败！");
        }

        //下面代码目的    删除图书结束后会返回删除之前所在页
        if(!"".equals(request.getParameter("bookName"))){
            try {
                String bookName = URLEncoder.encode(request.getParameter("bookName"), "UTF-8");
                return "redirect:/querybook.html?bookName=" + bookName + "&currentPage=" + request.getParameter("currentPage");
            }catch (Exception e){
                System.out.println("encode方法会报出异常，没办法1");
            }
        }
        if(!"".equals(request.getParameter("classId"))){
            return "redirect:/querybook2.html?classId="+request.getParameter("classId")+"&currentPage="+request.getParameter("currentPage");
        }
        return "redirect:/admin_books.html?currentPage="+request.getParameter("currentPage");

        // return "redirect:/admin_books.html";
    }

    /* ------------------------------分割线----------------------------------------*/

    /*读者    界面头部*/
    @RequestMapping("/reader_header.html")
    public ModelAndView reader_header() {
        return new ModelAndView("reader_header");
    }

    /*读者 查看全部书籍*/
    @RequestMapping("/reader_books.html")
    public ModelAndView readerBooks(HttpServletRequest request) {
        ArrayList<Book> books = bookService.getAllBooks();
        //session获取ReaderCard对象（包含读者账号 、读者密码、 读者名字) ----读者登录就会产生
        ReaderCard readerCard = (ReaderCard) request.getSession().getAttribute("readercard");
        ArrayList<Lend> myAllLendList = lendService.myLendList(readerCard.getReaderId());
        //没有归还的书籍归还日期为空
        ArrayList<Lend> myLendList = new ArrayList<>();
        for (Lend lend : myAllLendList) {
            // 是否已归还
            if (lend.getBackDate() == null) {
                myLendList.add(lend);
            }
        }
        ModelAndView modelAndView = new ModelAndView("reader_books");

        //分页需要
        Page page = getPage(request, books);                             //分页数据信息
        ArrayList<Book> booksByPage = bookService.getAllBooksByPage(page);//当前页的图书集合
        modelAndView.addObject("page", page);
        modelAndView.addObject("url", "/reader_books.html");

        modelAndView.addObject("books", booksByPage);
        modelAndView.addObject("myLendList", myLendList);
        ArrayList<Class> classList = bookService.queryAllClassInfo();           //我觉得这个登录的时候通过session存储起来比较好
        modelAndView.addObject("classList", classList);
        return modelAndView;
    }

    /*读者    模糊查询图书（书名、作者名）*/
    @RequestMapping("/reader_querybook_do.html")
    public ModelAndView readerQueryBookDo(HttpServletRequest request, String bookName) {
        ModelAndView modelAndView = new ModelAndView("reader_books");
        ArrayList<Class> classList = bookService.queryAllClassInfo();           //我觉得这个登录的时候通过session存储起来比较好
        modelAndView.addObject("classList", classList);
        ArrayList<Book> books = bookService.queryBook(bookName);
        if (books.size() > 0) {
            Page page = getPage(request, books);                                  //分页数据信息
            ArrayList<Book> booksByPage = bookService.queryBookByPage(bookName, page.getBeginIndex(), everyPage);//当前页的图书集合
            modelAndView.addObject("page", page);
            modelAndView.addObject("url", "/reader_querybook_do.html");
            modelAndView.addObject("bookName", bookName);
            modelAndView.addObject("books", booksByPage);
            return modelAndView;
        } else {
            ModelAndView modelAndView2 = new ModelAndView("reader_books", "error", "没有匹配的图书");
            modelAndView2.addObject("classList", classList);
            return modelAndView2;
        }
    }

    /*管理员   模糊查询图书  (图书类别id）*/
    @RequestMapping("/reader_querybook_do2.html")
    public ModelAndView readerQueryBookDo2(HttpServletRequest request, long classId) {
        ModelAndView modelAndView = new ModelAndView("reader_books");
        ArrayList<Class> classList = bookService.queryAllClassInfo();           //我觉得这个登录的时候通过session存储起来比较好
        modelAndView.addObject("classList", classList);
        ArrayList<Book> books = bookService.queryBook2(classId);
        if (books.size() > 0) {
            Page page = getPage(request, books);                                  //分页数据信息
            ArrayList<Book> booksByPage = bookService.queryBook2ByPage(classId, page.getBeginIndex(), everyPage);//当前页的图书集合
            modelAndView.addObject("books", booksByPage);
            modelAndView.addObject("url", "/reader_querybook_do2.html");
            modelAndView.addObject("page", page);
            modelAndView.addObject("classId", classId);
            return modelAndView;
        } else {
            ModelAndView modelAndView2 = new ModelAndView("reader_books", "error", "没有匹配的图书");
            modelAndView2.addObject("classList", classList);
            return modelAndView2;
        }
    }

    /*读者  查看书籍详情*/
    @RequestMapping("/reader_book_detail.html")
    public ModelAndView readerBookDetail(HttpServletRequest request) {
        long bookId = Long.parseLong(request.getParameter("bookId"));
        Book book = bookService.getBook(bookId);
        ModelAndView modelAndView = new ModelAndView("reader_book_detail");
        modelAndView.addObject("detail", book);
        return modelAndView;
    }

}
